<template>
	<view class="content">
		<view class="bgColor">
			<image src="/static/login/loginBg.png" mode="aspectFill"></image>
		</view>
		<view class="msgCont">
			<view class="appName">
				小润动销
			</view>
			<view class="inptBox">
				<image src="@/static/login/phoneIcon.png" mode=""></image>
				<input type="text" v-model="username" placeholder="请输入登录手机号码" placeholder-style="color:#B2B6BC;" />
			</view>
			<view class="inptBox">
				<image src="@/static/login/mima.png" mode=""></image>
				<input :password="typePassword" v-model="passwordLogin" placeholder="请输入登录密码"
					placeholder-style="color:#B2B6BC;" />
				<view class="inptBoxEye" @click="eyeClick">
					<image v-if="!typePassword" src="@/static/login/eye.png" mode=""
						style="width: 30.13rpx;height: 20.13rpx;"></image>
					<image v-if="typePassword" src="@/static/login/eyeBy.png" mode=""
						style="width: 30.13rpx;height: 15.38rpx;"></image>
				</view>
			</view>
			<view class="btnLogin" @click="login">
				登录
			</view>
		</view>

		<!-- 修改登录密码弹窗 -->
		<u-popup :show="show" :safeAreaInsetBottom="false" mode="center" :round="12.82" @close="close" @open="open">
			<view class="popupBox">
				<view class="popupTit">
					请修改登录密码<text>每3个月需重新设置密码</text>
				</view>
				<view class="popupInpt">
					<view class="popupInptName">新密码</view>
					<view class="popupInptText">
						<input v-model="newPassword" type="text" placeholder="请输入"
							placeholder-style="color: #7F8494;" />
					</view>
				</view>
				<view class="popupInpt">
					<view class="popupInptName">确认密码</view>
					<view class="popupInptText">
						<input v-model="confirmPassword" type="text" placeholder="请输入"
							placeholder-style="color: #7F8494;" />
					</view>
				</view>
				<view class="popupBtn" @click="submitUpdatePassword">
					确定
				</view>
			</view>
		</u-popup>

		<!-- 手势密码设置弹窗 -->
		<u-popup :show="gestureShow" :safeAreaInsetBottom="false" mode="center" :round="12.82" @close="gestureClose"
			@open="gestureOpen" :maskClosable="false" :closeOnClickOverlay="false" :lockScroll="true">
			<view class="gestureBox" style="padding: 48.08rpx 0 58.33rpx;">
				<view class="gestureTit">
					{{ gestureMode === 'set' ? '请设置手势密码' : '请输入手势密码' }}
				</view>
				<view class="gestureTitWidth" id="gestureContainer">
					<gesture-password :containerWidth="screenWidth" @change="handleGestureChange"></gesture-password>
				</view>
				<view class="gestureTip">
					至少连接4个点
				</view>
				<view class="gestureForgot" v-if="gestureMode !== 'set'" @click="forgotGesturePassword">
					忘记手势密码
				</view>
			</view>
		</u-popup>
	</view>
</template>

<script setup>
	import gesturePassword from '@/components/gzz-gesture/gesture-password.vue';
	import {
		ref,
		onMounted
	} from 'vue';
	import {
		onLoad
	} from '@dcloudio/uni-app';
	import {
		authLogin,
		updateGuestPassword,
		verifyGesturePassword,
		updateUserPassword
	} from '@/api/interface.js';

	// 表单数据
	const username = ref("");
	const passwordLogin = ref("");
	const typePassword = ref(true);

	// 弹窗控制
	const show = ref(false); // 修改密码弹窗
	const gestureShow = ref(false); // 手势密码弹窗
	const gestureMode = ref('set'); // 'set' 设置 / 'verify' 验证

	// 修改密码弹窗数据
	const newPassword = ref("");
	const confirmPassword = ref("");

	// 手势相关
	const screenWidth = ref(300); // 默认宽度
	
	// 获取手势容器宽度
	const getParentWidth = () => {
		setTimeout(() => {
			// #ifdef MP-WEIXIN
			const query = uni.createSelectorQuery();
			query.select('#gestureContainer').boundingClientRect(res => {
				if (res && res.width) {
					screenWidth.value = parseInt(res.width);
				}
			}).exec();
			// #endif

			// #ifdef H5
			const el = document.querySelector('#gestureContainer');
			if (el) {
				screenWidth.value = el.offsetWidth;
			}
			// #endif
		}, 50);
	};

	// 手势绘制完成回调
	const handleGestureChange = (points) => {
		if (!Array.isArray(points) || points.length < 4) {
			uni.showToast({
				title: '至少连接4个点',
				icon: 'none'
			});
			return;
		}

		const plainPoints = [...points]; // 脱响应式

		if (gestureMode.value === 'set') {
			// 设置手势密码
			updateGuestPassword({
				password: JSON.stringify(plainPoints) // 或根据后端要求改为 { points: plainPoints }
			}).then(res => {
				if(res.data){
					uni.showToast({
						title: '手势密码设置成功',
						icon: 'success'
					});
					// 设置成功后，标记启用且本次会话已验证
					uni.setStorageSync('gestureEnabled', true);
					uni.setStorageSync('gestureVerified', true);
					uni.reLaunch({
						url:"/pages/index/index"
					})
				}else{
					uni.showToast({
						title: '设置失败，请重试',
						icon: 'error'
					});
					uni.clearStorage();
				}
				gestureShow.value = false;
			}).catch(err => {
				uni.showToast({
					title: '设置失败，请重试',
					icon: 'error'
				});
			});
		} else {
			// 验证手势密码（当前登录流程不会触发，保留扩展）
			verifyGesturePassword({
				password: JSON.stringify(plainPoints)
			}).then(res => {
				if(res.data){
						uni.showToast({
							title: '验证成功',
							icon: 'success'
						});
						// 验证通过，标记本次会话已验证
						uni.setStorageSync('gestureVerified', true);
						uni.reLaunch({
							url:"/pages/index/index"
						})
				}else{
					uni.showToast({
						title: '手势密码错误',
						icon: 'error'
					});
					uni.clearStorage();
				}
				gestureShow.value = false;
				
			}).catch(err => {
				uni.showToast({
					title: '手势密码错误',
					icon: 'error'
				});
			});
		}
	};
	
	const toHome = () => {
		uni.navigateTo({
			url:"/pages/index/index"
		})
	}


	// 登录
	const login = () => {
		if (!username.value) {
			uni.showToast({
				title: "请输入手机号",
				icon: "none"
			});
			return;
		}
		if (!passwordLogin.value) {
			uni.showToast({
				title: "请输入登录密码",
				icon: "none"
			});
			return;
		}
		
		authLogin({
			username: username.value,
			password: passwordLogin.value
		}).then(res => {
		
			if (res.data.needUpdatePassWord) {
				show.value = true;
			} else if (res.data.needSetGesturePassWord) {
				gestureMode.value = 'set';
				gestureShow.value = true;
				uni.setStorageSync("token", res.data.accessToken);
				uni.setStorageSync("userId", res.data.userId);
				uni.setStorageSync("password", passwordLogin.value);
				// 标记已启用手势校验，待设置完成后生效
				uni.setStorageSync('gestureEnabled', true);
			} else {
				uni.setStorageSync("token", res.data.accessToken);
				uni.setStorageSync("userId", res.data.userId);
				uni.setStorageSync("password", passwordLogin.value);
				// 已存在手势密码，进入输入校验模式
				uni.setStorageSync('gestureEnabled', true);
				gestureMode.value = 'input';
				gestureShow.value = true;
			}
		}).catch(err => {
			uni.showToast({
				title: '登录失败',
				icon: 'error'
			});
		});
	};

	// 修改密码弹窗操作
	const close = () => {
		show.value = false;
	};
	const open = () => {};

	const submitUpdatePassword = () => {
		if (!newPassword.value) {
			uni.showToast({
				title: '请输入新密码',
				icon: 'none'
			});
			return;
		}
		if (newPassword.value !== confirmPassword.value) {
			uni.showToast({
				title: '两次密码不一致',
				icon: 'none'
			});
			return;
		}
		updateUserPassword({
			id: uni.getStorageSync("userId"),
			password: newPassword.value
		}).then(res => {
			uni.setStorageSync("password",newPassword.value)
			uni.showToast({
				title: '密码重置成功，请重新登陆',
				icon: 'success'
			});
			show.value = false;
		}).catch(err => {
			uni.showToast({
				title: '设置失败，请重试',
				icon: 'error'
			});
		});


	};

	// 手势弹窗操作
	const gestureClose = () => {
		gestureShow.value = false;
	};
	const gestureOpen = () => {
		getParentWidth();
	};

	// 忘记手势密码
	const forgotGesturePassword = () => {
		// 将模式切换为设置模式
		gestureMode.value = 'set';
		uni.showToast({
			title: '请重新设置手势密码',
			icon: 'none'
		});
	};

	// 切换密码可见性
	const eyeClick = () => {
		typePassword.value = !typePassword.value;
	};

	// 获取用户信息并跳转首页
	const getUserInfo = () => {


		// 实际项目中应调用 getUserInfo 接口
		// uni.switchTab({
		// 	url: '/pages/index/index'
		// });
	};
	
	
	// 页面加载
	onMounted(() => {
		// 可在此预加载或其他初始化
	});
	
	// 页面加载
	onLoad(() => {
		const token = uni.getStorageSync('token');
		const gestureEnabled = uni.getStorageSync('gestureEnabled');
		const gestureVerified = uni.getStorageSync('gestureVerified');
		
		if (token && gestureEnabled && gestureVerified !== true) {
			// 已登录且开启手势，但本次会话尚未验证，弹出手势输入
			gestureMode.value = 'input';
			gestureShow.value = true;
			getParentWidth();
		} else if (token) {
			// 已登录且无需手势校验，直接进入首页
			uni.reLaunch({
				url: "/pages/index/index"
			});
		}
	});
</script>

<style lang="scss" scoped>
	.bgColor {
		position: fixed;
		top: 0;
		left: 0;
		right: 0;
		bottom: 0;
		width: 100%;
		height: 100vh;

		image {
			width: 100%;
			height: 100%;
		}
	}

	.msgCont {
		position: absolute;
		top: 55%;
		left: 0;
		width: 100%;
	}

	.appName {
		font-weight: 400;
		font-size: 55.13rpx;
		color: #692E0B;
		text-align: center;
		width: 100%;
		margin-bottom: 69rpx;
	}

	.inptBox {
		width: 639.74rpx;
		height: 93.59rpx;
		border-radius: 46.79rpx;
		background: #f6f9ff;
		margin: 0 auto 23.72rpx;
		display: flex;
		align-items: center;
		padding: 0 46.79rpx;
		box-sizing: border-box;

		image {
			width: 36.54rpx;
			height: 39.74rpx;
		}

		input {
			font-size: 29.49rpx;
			font-weight: 400;
			margin-left: 23rpx;
			flex: 1;
		}

		.inptBoxEye {
			padding-left: 20rpx;
			box-sizing: border-box;
		}
	}

	.btnLogin {
		width: 639rpx;
		height: 93.59rpx;
		border-radius: 46.79rpx;
		background: #f89e30;
		box-shadow: 0 2.56rpx 15.38rpx 0 #ef8d1e6b;
		font-weight: 500;
		font-size: 32.05rpx;
		color: #FFFFFF;
		display: flex;
		align-items: center;
		justify-content: center;
		margin: 12rpx auto 0;
	}

	.popupBox {
		padding: 48.08rpx 42.95rpx 58.33rpx;
		box-sizing: border-box;

		.popupTit {
			font-weight: 500;
			font-size: 33.33rpx;
			color: #1C2027;
			margin-bottom: 46.79rpx;

			text {
				font-weight: 400;
				font-size: 24.36rpx;
				color: #FF0000;
				margin-left: 16.67rpx;
			}
		}

		.popupInpt {
			display: flex;
			align-items: center;
			margin-bottom: 39.74rpx;

			.popupInptName {
				font-size: 26.92rpx;
				text-align: right;
				font-weight: 400;
				color: #1C2027;
				width: 120rpx;
			}

			.popupInptText {
				margin-left: 18.59rpx;
				flex: 1;
				height: 80.77rpx;
				border-radius: 10.26rpx;
				background: #f4f6f991;
				font-size: 25.64rpx;
				display: flex;
				align-items: center;
				padding: 0 28.85rpx;
				box-sizing: border-box;
				border: 1px solid #E3E6ED;

				input {
					flex: 1;
					font-size: 25.64rpx;
				}
			}
		}

		.popupBtn {
			width: 435.9rpx;
			height: 83.33rpx;
			border-radius: 41.67rpx;
			background: linear-gradient(-90deg, #feaf38, #f98434);
			box-shadow: 0 3.85rpx 4.49rpx 0 #f984344d;
			font-size: 32.05rpx;
			color: #FFFFFF;
			display: flex;
			align-items: center;
			justify-content: center;
			margin: 36rpx auto 0;
		}
	}

	.gestureBox {
		width: 643.59rpx;
		padding: 48.08rpx 42.95rpx 58.33rpx;
		box-sizing: border-box;

		.gestureTit {
			font-weight: 500;
			font-size: 33.33rpx;
			color: #1C2027;
			text-align: center;
		}

		.gestureTip {
			font-size: 24.36rpx;
			font-weight: 400;
			color: #828384;
			text-align: center;
			margin-top: 20rpx;
		}
		.gestureForgot {
			font-size: 26.92rpx;
			font-weight: 400;
			color: #3776f5;
			text-align: center;
			margin-top: 30rpx;
			padding-top: 20rpx;
			border-top: 1rpx solid #e5e5e5;
			width: 90%;
			margin-left: 5%;
		}
	}
</style>